//
//  AgeVC.swift
//  ShareUmbrella
//
//  Created by duanmingyang on 2017/9/17.
//  Copyright © 2017年 尧尚信息科技. All rights reserved.
//

import UIKit
import YSKit
import TSMessages

class AgeVC: YSBaseViewController,UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource{
    let kScreenHeight = UIScreen.main.bounds.size.height
    let kScreenWidth = UIScreen.main.bounds.size.width
    var selfTableView:UITableView!
    var valueTextField:UITextField!
    
    override func setup() {
        super.setup()
    }
    
    /*
     *
     * 界面布局初始化
     */
    override func buildUI() {
        super.buildUI()
        self.title = I18n("usercenter.age.title")
        
        self.edgesForExtendedLayout = UIRectEdge(rawValue: 0)
        
        self.initBackgourndViewColor()
        self.addSelfTableView()
    }
    
    //
    override func buildRx() {
        super.buildRx()
    }
    
    //RGB
    func RGB(r:CGFloat,_ g:CGFloat,_ b:CGFloat) -> UIColor{
        return UIColor(red: (r)/255.0, green: (g)/255.0, blue: (b)/255.0, alpha: 1.0)
    }
    
    //初始化背景颜色
    func initBackgourndViewColor() {
        self.view.backgroundColor = RGB(r: 239, 239, 243)
    }
    
    //更新信息
    func updateUserInfo(){
        HUD.show()
        _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(UserAPI.updateUserInfo(token: Auth.token, value: valueTextField.text!, type: .age))).subscribe(onNext: {(data) in
            //
            HUD.hide()
            //延迟1s返回上一层
            let retcode = data?["retcode"].int
            if(retcode == 0){
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1*NSEC_PER_SEC))/Double(NSEC_PER_SEC)) {
                    TSMessage.showNotification(withTitle: I18n("修改成功"), type: .success)
                    UserService.sharedInstance.age.value = self.valueTextField.text
                    self.navigationController?.popViewController(animated: true)
                }
            }else{
                HUD.show(HudIcon.failure, title: "失败")
            }
            
        }, onError: {(ErrorType) in
            HUD.hide()
            self.handle(withError: ErrorType)
        })
    }
    
    //添加一个tableview
    func addSelfTableView(){
        
        selfTableView = UITableView.init(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight), style: UITableViewStyle.grouped)
        selfTableView.dataSource = self
        selfTableView.delegate = self
        selfTableView.backgroundColor = UIColor.clear
        selfTableView.separatorStyle = UITableViewCellSeparatorStyle.none;
        selfTableView.showsHorizontalScrollIndicator = false
        selfTableView.showsVerticalScrollIndicator = false
        self.view.addSubview(selfTableView)
    }
    
    //MARK:UITableView DataSource
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let iderntify:String = "swiftCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: iderntify) as? InputCell
        if(cell == nil){
            cell=InputCell(style: UITableViewCellStyle.default
                , reuseIdentifier: iderntify);
            
        }
        
        valueTextField = cell?.valueField
        
        valueTextField.becomeFirstResponder()
        valueTextField.delegate = self
        valueTextField.returnKeyType = UIReturnKeyType.done
        valueTextField.text = UserService.sharedInstance.age.value
        valueTextField.keyboardType = UIKeyboardType.numberPad
        valueTextField.placeholder = "岁数"
        valueTextField.addDoneOnKeyboardWithTarget(self, action: #selector(self.done))
        
        
        return cell!
    }
    
    //MARK:UITableView Delegate
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selfTableView?.deselectRow(at: indexPath, animated: true)
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        return 10
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView.init(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 20))
        if(section == 0){
            view.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: 0)
        }
        return view
    }
    
    //MARK:UITextField Delegate
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        
        // 结束编辑
        //textField.resignFirstResponder()
        self.done()
        
        return true
    }
    
    public func done() {
        valueTextField.resignFirstResponder()
        self.updateUserInfo()
    }
}
